#! encoding:utf-8

import logging
from colorlog import ColoredFormatter
from logging.handlers import RotatingFileHandler
import sys  
reload(sys)  
sys.setdefaultencoding('utf8')  


class Log(object):
	"""docstring for Log"""
	def __init__(self,file_path,level,color,mode = 'a',logger_name=__name__):
		self.mode = mode
		self.file_path = file_path
		self.log_level = level
		self.log_color = color
		if self.log_level == 'TRACE':
			TRACE = 5
			logging.addLevelName(TRACE,'TRACE')
			self.log_color['TRACE'] = 'purple,bg_white'
		self.logger = logging.getLogger(logger_name)
		self.logger.setLevel(self.log_level)
		self.formatter = ColoredFormatter(
			'%(log_color)s%(asctime)s Pro:%(process)d [line:%(lineno)d] %(levelname)s %(message)s',
			datefmt = None,#日期格式
			reset = True,
			log_colors = self.log_color,
			secondary_log_colors={},
			)

	def file_info_handle(self):
		file_rt_info_handler = RotatingFileHandler(
			filename=self.file_path,
			mode = 'a',
			maxBytes=100*1024*1024,
			backupCount=1
			)
		file_rt_info_handler.setLevel(self.log_level)
		file_rt_info_handler.setFormatter(self.formatter)
		return file_rt_info_handler


	def file_error_handle(self):
		file_rt_error_handler = RotatingFileHandler(
			filename = self.file_path + '.error',
			mode = 'a',
			maxBytes = 50*1024*1024,
			backupCount = 1
			)
		file_rt_error_handler.setLevel('ERROR')
		file_rt_error_handler.setFormatter(self.formatter)
		return file_rt_error_handler


	def stream_handler(self):
		chlr = logging.StreamHandler()
		chlr.setLevel(self.log_level)
		chlr.setFormatter(self.formatter)
		return chlr

	
	def main(self):
		self.logger.addHandler(self.file_info_handle())
		self.logger.addHandler(self.file_error_handle())
		self.logger.addHandler(self.stream_handler())
		return self.logger

if __name__ == '__main__':
	a = Log()
	print a.file_path
	print a.level
